package com.dhnsoft.代码随想录.栈与队列;

import java.util.Stack;

/**
 * ClassName: d05_150_逆波兰表达式求值
 * Package: com.dhnsoft.代码随想录.栈与队列
 * Description:
 *
 * @Author dhn
 * @Create 2024/3/27 12:37
 * @Version 1.0
 */
public class d05_150_逆波兰表达式求值 {

    public static void main(String[] args) {
        System.out.println(evalRPN(new String[]{"10","6","9","3","+","-11","*","/","*","17","+","5","+"}));
    }

    public static int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if(token.equals("+")){
                stack.push(stack.pop()+stack.pop());
            }
            else if(token.equals("-")){
                int num2 = stack.pop();
                int num1 = stack.pop();
                stack.push(num1-num2);
            }
            else if(token.equals("*")){
                stack.push(stack.pop()*stack.pop());
            }
            else if(token.equals("/")){
                int num2 = stack.pop();
                int num1 = stack.pop();
                stack.push(num1/num2);
            }
            else{
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }
}
